package com.baidumap.administrator.happystudy.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ab.dialog.loadingDialog.LoadingDialogUtil;
import com.ab.http.OnMessageResponse;
import com.ab.util.AbMathUtil;
import com.ab.util.ListUtils;
import com.ab.util.ToastUtil;
import com.ab.view.scrollview.KJScrollView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.adapter.SupermarketAdapter;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseActivity;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.model.Activities;
import com.baidumap.administrator.happystudy.model.MarketData;
import com.baidumap.administrator.happystudy.model.ShopList;
import com.baidumap.administrator.happystudy.utils.GlideUtil;
import com.baidumap.administrator.happystudy.view.SwipyRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.socks.library.KLog;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 描述：
 * 作者：xiaoxing on 17/4/13 13:41
 * 邮箱：2235445233@qq.com
 */
public class WaiMaiGaoDeActivity extends AppBaseActivity implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, SwipyRefreshLayout.OnRefreshListener, OnMessageResponse, XBanner.XBannerAdapter {
    @Bind(R.id.product001)
    TextView product001;
    @Bind(R.id.tv_product001_price)
    TextView tvProduct001Price;
    @Bind(R.id.img_product002)
    ImageView imgProduct002;
     @Bind(R.id.img_product001)
    ImageView imgProduct001;
    @Bind(R.id.tv_product002_title)
    TextView tvProduct002Title;
    @Bind(R.id.img_product003)
    ImageView imgProduct003;
    @Bind(R.id.tv_product003_title)
    TextView tvProduct003Title;
    private AMap aMap;
    private MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private RadioGroup mGPSModeGroup;

    private TextView mLocationErrText;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    public ImageLoader loader;
    @Bind(R.id.list)
    ListView mListView;
    private ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private SupermarketAdapter mAdapter;
    private static int currentPage = 1;
    private ArrayList<Map<String, Object>> arrayList;


    @Bind(R.id.main_SwipyRefreshLayout)
    SwipyRefreshLayout mSwipyRefreshLayout;


    private Double mLatitude, mLongitude;//维度、精度
    private String mAddress;

    private String mCatrgoryId;
    ArrayList<HashMap<String, Object>> result = new ArrayList<>();
    private String mTitle;//标题

    @Bind(R.id.xbanner)
    XBanner mXBanner;

    @Bind(R.id.kj_scrool)
    KJScrollView kj_scrool;

    private List<Integer> mImgesUrl;
    private List<String> mBannerDataList;
    HashMap<String, MarketData> mHashMap = new HashMap<>();

    private int mProduct001, mProduct002, mProduct003;

    @Override
    public int bindLayout() {
        return R.layout.activity_wai_mai_gao_de;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        getBundleValue();
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(mSavedInstanceState);// 此方法必须重写
        init();
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        iniView();
        LoadingDialogUtil.showGifdialog(getSupportFragmentManager());
    }


    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        setHeaderBack();
        setHeaderTitle(mTitle);
        initXBanner();
        kj_scrool.scrollTo(0, 0);
    }

    private void getBundleValue() {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {

            mCatrgoryId = bundle.getString("category_id");
            mTitle = bundle.getString("title");
        }
    }

    private void iniView() {
        // 设置分页第一页的索引 默认为0
        mSwipyRefreshLayout.setFirstIndex(currentPage);
        // 监听事件
        mSwipyRefreshLayout.setOnRefreshListener(this);
        // LoadImage初始化
        loader = ImageLoader.getInstance();
        currentPage = 1;
        mAdapter = new SupermarketAdapter(this, loader);

        Api.shopActivites(this);

    }

    /**
     * 初始化
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

        mLocationErrText = (TextView) findViewById(R.id.location_errInfo_text);
        mLocationErrText.setVisibility(View.GONE);
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setupLocationStyle();
    }

    private void setupLocationStyle() {
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.mipmap.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mLocationErrText.setVisibility(View.GONE);
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                mLatitude = amapLocation.getLatitude();
                mLongitude = amapLocation.getLongitude();

                LatLng marker1 = new LatLng(mLatitude, mLongitude);
                //设置中心点和缩放比例
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
                aMap.moveCamera(CameraUpdateFactory.zoomTo(13));


                Api.shopList(WaiMaiGaoDeActivity.this, 1, mCatrgoryId, mLatitude, mLongitude);

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
//                mLocationErrText.setVisibility(View.VISIBLE);
//                mLocationErrText.setText(errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }


    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

        if (url.equals(Constant.SHOP_LIST) && jo != null) {
            ShopList shopList = new ShopList(jo.toString());

            if (shopList != null) {


                if (shopList.getCode().equals("200")) {

                    List<ShopList.DataBean> dataBeanList = shopList.getData();


                    HashMap<String, Object> map = null;

                    for (int i = 0; i < dataBeanList.size(); i++) {

                        LatLng latLng = new LatLng(Double.parseDouble(dataBeanList.get(i).getLat()), Double.parseDouble(dataBeanList.get(i).getLng()));

                        MarkerOptions markerOptions = new MarkerOptions().anchor(0.5f, 0.5f)
                                .position(latLng)
                                .draggable(true)
                                .icon(BitmapDescriptorFactory.defaultMarker(R.mipmap.hongse))
                                .draggable(true);


                        Marker marker = aMap.addMarker(markerOptions);

                        MarketData marketData = new MarketData();
                        marketData.setShop_id(dataBeanList.get(i).getShop_id());
                        marketData.setShop_name(dataBeanList.get(i).getShop_name());

                        mHashMap.put(marker.getId(), marketData);


                        map = new HashMap<>();
                        map.put("shop_id", dataBeanList.get(i).getShop_id());
                        map.put("shop_name", dataBeanList.get(i).getShop_name());
                        map.put("shop_img", Constant.DOMAIN + dataBeanList.get(i).getLogo());
                        map.put("shop_rating", dataBeanList.get(i).getShop_star());
                        map.put("shop_distance", AbMathUtil.round(dataBeanList.get(i).getDistance(), 2));
                        map.put("shop_walk_time", dataBeanList.get(i).getDelivery_time());
                        result.add(map);

                    }

                    list.addAll(result);//

                    ListUtils.removeDuplicate(list);

                    currentPageAdd(list);
                    mAdapter.bindData(list);

                    if (currentPage == 1) {

                        mListView.setAdapter(mAdapter);

                    }
                    mAdapter.notifyDataSetChanged();

                    ListUtils.setListViewHeightBasedOnChildren(mListView);
                } else {
                    ToastUtil.showMessage(this, shopList.getMsg());
                }
            }
            mSwipyRefreshLayout.setRefreshing(false);
        }


        if (url.equals(Constant.SHOP_ACTIVITIES) && jo != null) {
            Activities activities = new Activities(jo.toString());

            if (activities != null) {


                if (activities.getCode().equals("200")) {

                    List<Activities.DataBean> dataBeanList = activities.getData();

                    if (dataBeanList.size() > 0) {

                        product001.setText(dataBeanList.get(0).getProduct_name());
                        tvProduct001Price.setText("￥" + dataBeanList.get(0).getPrice());
                        mProduct001 = Integer.parseInt(dataBeanList.get(0).getProduct_id());
                        GlideUtil.displayImg(this, dataBeanList.get(0).getProduct_pic1(), imgProduct001);
                        KLog.e("mProduct001=" + mProduct001);
                    }
                    if (dataBeanList.size() > 1) {
                        tvProduct002Title.setText(dataBeanList.get(1).getProduct_name());
                        GlideUtil.displayImg(this, dataBeanList.get(1).getProduct_pic1(), imgProduct002);
                        mProduct002 = Integer.parseInt(dataBeanList.get(1).getProduct_id());
                        KLog.e("mProduct002=" + mProduct002);
                    }
                    if (dataBeanList.size() > 2) {
                        tvProduct003Title.setText(dataBeanList.get(2).getProduct_name());
                        GlideUtil.displayImg(this, dataBeanList.get(2).getProduct_pic1(), imgProduct003);
                        mProduct003 = Integer.parseInt(dataBeanList.get(2).getProduct_id());
                        KLog.e("mProduct003=" + mProduct003);
                    }

                } else {
                    ToastUtil.showMessage(this, activities.getMsg());
                }
            }

        }

    }

    protected void currentPageAdd(ArrayList mListView) {
        KLog.e("========" + currentPage);
        if (mListView.size() % 20 == 0 && mListView.size() > 0) {
            currentPage++;
        }
    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }

    /**
     * 下拉刷新
     *
     * @param index 当前分页索引
     */
    @Override
    public void onRefresh(int index) {
        currentPage = 1;

        result.clear();
        list.clear();
        mAdapter.notifyDataSetChanged();
        Api.shopList(this, currentPage, mCatrgoryId, mLatitude, mLongitude);
    }

    /**
     * 加载更多
     *
     * @param index 当前分页索引
     */
    @Override
    public void onLoad(int index) {
//        mSwipyRefreshLayout.setRefreshing(false);
        Api.shopList(this, currentPage, mCatrgoryId, mLatitude, mLongitude);

    }

    /**
     * 初始化轮播图
     */

    private void initXBanner() {

        mImgesUrl = new ArrayList<>();

        int[] imgages = {R.mipmap.waimai_banner_001, R.mipmap.waimai_banner_002, R.mipmap.waimai_banner_003, R.mipmap.waimai_banner_004, R.mipmap.waimai_banner_005};

        for (int i = 0; i < imgages.length; i++) {
            mImgesUrl.add(imgages[i]);

        }

        //添加广告数据
        mXBanner.setData(mImgesUrl, null);//第二个参数为提示文字资源集合
        mXBanner.setmAdapter(this);
    }

    @Override
    public void loadBanner(XBanner banner, Object model, View view, int position) {

        GlideUtil.displayImgBanner(this, mImgesUrl.get(position), view);
    }


    @OnClick({R.id.ll_canyin, R.id.ll_chaoshi, R.id.ll_xianhua, R.id.ll_xiawucha, R.id.ll_shuiguo, R.id.rl_001, R.id.rl_002, R.id.rl_003})
    public void onClick(View view) {
        Bundle bundle = new Bundle();

        switch (view.getId()) {
            case R.id.ll_canyin:
                bundle.putString("category_id", "199");
                bundle.putString("title", "餐饮");
                startBundleActivity(bundle, WaiMaiGoodsListActivity.class);
                break;
            case R.id.ll_chaoshi:
                bundle.putString("category_id", "198");
                bundle.putString("title", "超市");
                startBundleActivity(bundle, WaiMaiGoodsListActivity.class);
                break;
            case R.id.ll_xianhua:
                bundle.putString("category_id", "200");
                bundle.putString("title", "鲜花蛋糕");
                startBundleActivity(bundle, WaiMaiGoodsListActivity.class);
                break;
            case R.id.ll_xiawucha:
                bundle.putString("category_id", "201");
                bundle.putString("title", "下午茶");
                startBundleActivity(bundle, WaiMaiGoodsListActivity.class);
                break;
            case R.id.ll_shuiguo:
                bundle.putString("category_id", "202");
                bundle.putString("title", "水果生鲜");
                startBundleActivity(bundle, WaiMaiGoodsListActivity.class);
                break;
            case R.id.rl_001:
                if (mProduct001 > 0) {
                    bundle.putString("product_id", String.valueOf(mProduct001));
                    Intent it = new Intent(this, GoodDetailActivity.class);
                    it.putExtras(bundle);
                    startActivity(it);
                }
                break;
            case R.id.rl_002:
                if (mProduct002 > 0) {
                    bundle.putString("product_id", String.valueOf(mProduct002));
                    Intent it = new Intent(this, GoodDetailActivity.class);
                    it.putExtras(bundle);
                    startActivity(it);
                }
                break;
            case R.id.rl_003:
                if (mProduct003 > 0) {
                    bundle.putString("product_id", String.valueOf(mProduct003));
                    Intent it = new Intent(this, GoodDetailActivity.class);
                    it.putExtras(bundle);
                    startActivity(it);
                }
                break;
        }
    }

}
